package fr.generali.poc.statemachine.choregraphe;

import org.apache.camel.ExchangePattern;
import org.apache.camel.ProducerTemplate;
import org.slf4j.Logger;

import fr.generali.poc.statemachine.events.Event;
import fr.generali.poc.statemachine.model.Dossier;
import fr.generali.poc.statemachine.model.TransitionModel;
import fr.generali.poc.statemachine.transitions.UpdateSuspensTransition;

public class ChoregrapheImpl implements IChoregraphe {
	private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory
			.getLogger(ChoregrapheImpl.class);

	private UpdateSuspensTransition updateSuspensTransition;
	private ProducerTemplate camelTemplate;

	public void setCamelTemplate(ProducerTemplate camelTemplate) {
		this.camelTemplate = camelTemplate;
	}

	public void setUpdateSuspensTransition(
			UpdateSuspensTransition updateSuspensTransition) {
		this.updateSuspensTransition = updateSuspensTransition;
	}

	public Dossier execute(Dossier d, Event e) {
		Dossier doss = null;
		// On recupere les transitions a executer
		final TransitionModel transitionModel = d.getStatut().getTransition(d,
				e);
		LOGGER.debug("la transition est : " + transitionModel);
		// on met a jour le statut du dossier
		d.setStatut(transitionModel.getState());

		// On execute la transition
		if (UpdateSuspensTransition.NAME.equals(transitionModel
				.getTransitionName())) {
			// Sans camel

			doss = updateSuspensTransition.executeTransition(d, e);
		} else {
			// Avec Camel

			doss = (Dossier) camelTemplate.sendBody(
					transitionModel.getTransitionName(), ExchangePattern.InOut,
					d);
		}
		return doss;
	}
}
